package others;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by barton on 16-5-9.
 */
@SuppressWarnings("Duplicates")
public class CallableAndFuture {

    @Test
    public void test1() {
        Callable<Integer> callable = () -> (new Random().nextInt(100));

        FutureTask<Integer> future = new FutureTask<>(callable);

        new Thread(future).start();

        try {
            Thread.sleep(5000);
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test2() {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();

        Future<Integer> future = threadPool.submit(() -> (new Random().nextInt(100)));

        try {
            Thread.sleep(5000);
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
